package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    //新增地址
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        log.info("添加新地址：{}",addressBook);
        //绑定用户
        addressBook.setUserId(BaseContext.getCurrentId());
        //存储到数据库
        addressBookService.save(addressBook);

        return  R.success(addressBook);
    }


    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {

        log.info("addressBook:{}", addressBook);

        // 先将用户所有地址的isDefault改为0
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        luw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        luw.set(AddressBook::getIsDefault, 0);

        // SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(luw);

        // 再将传入的地址的isDefault设为1
        addressBook.setIsDefault(1);

        // SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }


    //根据id查询地址
    @GetMapping("/{id}")
    public R get(@PathVariable String id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook!=null){
            return  R.success(addressBook);
        }else{
            return  R.success("改地址不存在");
        }
    }

    //添加订单的时候需要判断当前的默认地址是哪个
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        //创建查询条件对象
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //查询当前用户的地址簿并且是默认的
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId())
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        //判断当前时候选择了默认地址
        if (addressBook!=null){
            return R.success(addressBook);
        }

        return R.error("请选择默认地址！");
    }


    @PutMapping
    public R<AddressBook> update(@RequestBody AddressBook addressBook) {

        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 用户端
     * 删除地址
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {

        log.info("删除地址：{}", ids);
        List<AddressBook> addressBooks = addressBookService.listByIds(ids);
        for (AddressBook addressBook : addressBooks) {
            if (addressBook.getIsDefault() == 1) {
                throw new CustomException("默认地址无法删除");
            }
        }
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }


    //查询当账户的所有地址
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
        //创建查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByDesc(AddressBook::getIsDefault);

        List<AddressBook> addressBooks = addressBookService.list(queryWrapper);

        return R.success(addressBooks);
    }

    //查询当前地址所在的经纬度
    @GetMapping("/baidu")
    public R<AddressBook> baidu(){
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();
        //创建addressBook查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        //匹配用户id，匹配当天默认地址
        queryWrapper.eq(AddressBook::getUserId,userId)
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        return R.success(addressBook);
    }
}
